
public class PeakDetectionAlgo {
	final public static int countPeaks(double[] values) {
		
		int slowMeanRate = 0, fastMeanRate = 0;
		
		slowMeanRate = 8;
		fastMeanRate = 12;

		
		int i =0;

		double[] macdDiff = new double[values.length];
		double[] mSlowA = new double[values.length];
		double[] mFastA = new double[values.length];

		
		// MACD params
		double mSlow = values[0], mFast = mSlow;
		int rSlow = slowMeanRate;
		int rFast = fastMeanRate;
		int index = 0;
		// zeroCrossCount params
		int res = 0;
		double cur = 0.0, next = 0.0;

		for (i=0;i<values.length;i++) {
			// -----------------------------------------
			// MACD ALGO
			mSlow = 0.0;mFast = 0.0;
			int mSlowCoef = 0, mFastCoef = 0;
			for (int j=0;j<rFast; j++) {
				index = i - (rFast/2) +j;
				if (index>=0 && index<values.length){
					mFast += values[index];
					mFastCoef++;
					int offset =((rFast-rSlow)/2);
					if ((j >= offset) && (j < offset+rSlow)){
							mSlow += values[index];
							mSlowCoef++;
					}
				}
			}
			mSlow /= (double)mSlowCoef;
			mFast /= (double)mFastCoef;
			
			mSlowA[i] = mSlow - 8.0;
			mFastA[i] = mFast - 8.0;
			
			macdDiff[i] = mFast-mSlow;
			// -----------------------------------------
			
			// -----------------------------------------
			// ZeroCrossCount within the same loop
			if (i>0) {
				cur = macdDiff[i-1];
				next = macdDiff[i];
				if (cur <= 0.) {
					if (next>0.) {
//						if (positive)
							res++;
						cur = next;
					}
				}
				if (cur >= 0.){
					if (next < 0.) {
//						if (!positive)
							res++;
						cur = next;
					}
				}
			}
			// -----------------------------------------
		}
		
		double[][] da = {values, mSlowA,mFastA};
		ToolBox.plot(da);
		
		return res;
	}	
}
